package cn.kduck.module.message.service.sender;

import cn.kduck.module.message.SmsServiceProperties;
import cn.kduck.module.message.service.SmsMessageSender;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class AliyunSmsMessageSender implements SmsMessageSender {

    private final SmsServiceProperties properties;

    private ObjectMapper objectMapper = new ObjectMapper();

    private Client client;

    public AliyunSmsMessageSender(SmsServiceProperties properties){
        this.properties = properties;
        initClient(properties);
    }

    @Override
    public boolean sendMessage(SenderParam param) {

        SendSmsRequest req = new SendSmsRequest();
        req.setPhoneNumbers(param.getPhoneNum());
        req.setSignName(properties.getSignName());
        req.setTemplateCode(param.getTemplateCode());

        //格式化短信模版参数
        String[] params = param.getParams();
        if(params.length > 0){
            Map<String,String> paramMap = new HashMap();
            for (String p : params) {
                int paramIndex = p.indexOf(":");
                if(paramIndex < 0){
                    throw new RuntimeException("短信模版参数格式错误，正确格式为name:value，实际传入值为：" + p);
                }
                paramMap.put(p.substring(0,paramIndex),p.substring(paramIndex + 1));
            }
            try {
                String formattedParam = objectMapper.writeValueAsString(paramMap);
                req.setTemplateParam(formattedParam);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("短信参数序列化错误:" + params,e);
            }
        }

        try {
            SendSmsResponse resp = client.sendSms(req);
            System.out.println(objectMapper.writeValueAsString(resp));
            return true;
        } catch (Exception e) {
            throw new RuntimeException("短信发送失败：" + param.getPhoneNum(),e);
        }
    }

    public void initClient(SmsServiceProperties param) {
        Config config = new Config()
                .setAccessKeyId(param.getSecretId())
                .setAccessKeySecret(param.getSecretKey());
        config.endpoint = "dysmsapi.aliyuncs.com";
        try {
            this.client = new Client(config);
        } catch (Exception e) {
            throw new RuntimeException("阿里云短信服务客户端创建错误",e);
        }
    }
}
